package
{
	import flash.desktop.NativeApplication;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	import flash.utils.ByteArray;
	import flash.utils.Dictionary;
	
	import as3sdk.utils.UtilXMLParse;
	
	/**
	 * ATF合并xml工具。 
	 * @author hanxianming
	 * 
	 */	
	public class ATFTransformTool extends Sprite
	{
		private var _fileList:Array;
		private var _urlLoader:URLLoader;
		private var _urlRequest:URLRequest;
		private var _curLoadFile:File;
		private var _configByteArray:ByteArray;
		private var _urlConfigLoader:URLLoader;
		
		private var loadConfigList:Vector.<FolderNode>;
		
		private var _curFolderNode:FolderNode;
		
		private var _appXML:String = "XML2ObjectTool.xml";
		
		private var _appBat:String = "app.bat";
		
		private var _configCompress:String = "configCompress.xml";
		
		private var _curAppId:String;
		
		private var _configNumber:int;
		
		private var atfDict:Dictionary = new Dictionary();
		private var xmlDict:Dictionary = new Dictionary();
		
		public function ATFTransformTool()
		{
			initizlize();
		}
		
		private function initizlize():void
		{
			
			_urlRequest = new URLRequest();
			
			_urlConfigLoader = new URLLoader();
			_urlConfigLoader.dataFormat = URLLoaderDataFormat.TEXT;
			_urlConfigLoader.addEventListener(Event.COMPLETE, urlConfigLoaderCompleteHandler);
			
			_urlRequest.url = "configCompress.xml";
			//			_urlRequest.url = _appXML;
			_urlConfigLoader.load(_urlRequest);
			
			_urlLoader = new URLLoader();
			
			_urlLoader.dataFormat = URLLoaderDataFormat.TEXT;
			_urlLoader.addEventListener(Event.COMPLETE, urlLoaderCompleteHandler);

		}
		
		protected function urlConfigLoaderCompleteHandler(event:Event):void
		{
			loadConfigList = new Vector.<FolderNode>();
			
			var xml:XML = new XML(_urlConfigLoader.data);
			var configObject:Object = xml2Object(xml);
			
			var tempFile:File;
			var folderNode:FolderNode;
			
			for each (var item:Object in configObject) 
			{
				if (item is String)
				{
					continue;
				}
				
				tempFile = File.applicationDirectory;
				tempFile.nativePath = item["folder"];
				
				folderNode = new FolderNode();
				folderNode.copyMoveTarget = item.copyMoveTarget;
				folderNode.folder = item.folder;
				folderNode.exportName = item.exportName;
				folderNode.command = item.command;
				folderNode.commandSourceFile = item.commandSourceFile;
				try
				{
					folderNode.fileList = tempFile.getDirectoryListing();
				} 
				catch(error:Error) 
				{
					trace("[error] File.getDirectoryListing() error  " + tempFile.nativePath);
					continue;
				}
				for each (var item1:Object in item) 
				{
					if (item1 is String)
					{
						continue;
					}
					folderNode.compressList.push(item1["configName"]);
				}
				
				loadConfigList.push(folderNode);
			}
			
			loadFolder();			
		}		
		
		private function loadFolder():void
		{
			if (loadConfigList.length <= 0)
			{
				trace("[info] all completed......" + new Date().toString());
				
				NativeApplication.nativeApplication.exit();
				
				
				return;
			}
			
			_curFolderNode = loadConfigList.shift();
			
			_fileList = _curFolderNode.fileList;
			
			_configNumber = _fileList.length;
			
			loadFileList();
		}
		
		private function loadFileList():void
		{
			if (_fileList.length <= 0)
			{
				saveFile();				
				loadFolder();
				return;
			}
			
			var tempFile:File;
			
			tempFile = _fileList.pop();
			
			if (tempFile.isDirectory)
			{
				loadFileList();
				return;
			}
			
			_curLoadFile = tempFile;
			
			_urlRequest.url = tempFile.url;
			
			if (_curLoadFile.extension == "atf")
			{
				_urlLoader.dataFormat = URLLoaderDataFormat.BINARY;
			}
			else if(_curLoadFile.extension == "xml")
			{
				_urlLoader.dataFormat = URLLoaderDataFormat.TEXT;
			}
			
			_urlLoader.load(_urlRequest);
			
		}
		
		protected function urlLoaderCompleteHandler(event:Event):void
		{
			var tempName:String = _curLoadFile.name.replace("." + _curLoadFile.extension, "");

			if (_curLoadFile.extension == "atf")
			{
				var byteArray:ByteArray = new ByteArray();
				var tempByte:ByteArray = (_urlLoader.data as ByteArray); 
				tempByte.readBytes(byteArray);
				atfDict[tempName] = byteArray;
			}
			else if(_curLoadFile.extension == "xml")
			{
				var xml:XML = new XML(_urlLoader.data);
				xmlDict[tempName] = xml;
			}
			
			loadFileList();
		}
		
		private function saveFile():void
		{
			var fileStream:FileStream;
			try
			{
				for (var name:String in atfDict) 
				{
					var tempFile:File = File.applicationDirectory;
					tempFile.nativePath = _curFolderNode.copyMoveTarget + File.separator + name + ".xatf";
					fileStream = new FileStream();
					fileStream.open(tempFile, FileMode.WRITE);
					
					var tempByte:ByteArray = atfDict[name];
					
					if (xmlDict[name] != null)
					{
						var tempPosition:int = tempByte.length;
						tempByte.position = tempPosition;
						var tempString:String = XML(xmlDict[name]).toXMLString(); 
						tempByte.writeUTFBytes(tempString);
						tempByte.writeUnsignedInt(tempString.length);
						trace("[XML-ATF][info] " + " copyMove " + tempFile.nativePath + ".....");
					}
					else
					{
						trace("[ATF][info] " + " copyMove " + tempFile.nativePath + ".....");
					}
					
					fileStream.writeBytes(tempByte);
					fileStream.close();
				}
				
			}catch (e:Error) 
			{
				trace("[error] fileStream error：" + tempFile.nativePath);
			}
			fileStream = null;
		}
		
		
		public static function xml2Object(xml:XML):Object
		{
			return UtilXMLParse.xml2Object(xml);
		}
	}
}

class FolderNode
{
	public var exportName:String;
	public var folder:String;
	public var compressList:Vector.<String> = new Vector.<String>();
	public var fileList:Array;
	public var copyMoveTarget:String;
	public var sourceDirectory:String;
	public var command:String;
	public var commandSourceFile:String;
}